//
//  COAudioPlayer.swift
//  CocoProject
//
//  Created by Vill on 2023/11/15.
//

import Foundation

class COAudioPlayer{
    
    static let shared = COAudioPlayer()
    
    var numberOfLoops = -1
    private var audioPlayer: AVAudioPlayer?
    
    init() {
        print("注册了 ------------ ")
        NotificationCenter.default.addObserver(self, selector: #selector(beginInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)
    }
    
    @objc private func beginInterruption(notification: Notification) {
        if let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSession.InterruptionType {
            if type == .began {
                print("中断了 ----------------")
                audioPlayer?.pause()
            }else {
                print("继续播放了 ---------------")
                audioPlayer?.play()
            }
        }
    }
    
    func preparePlay(url: URL) {
        if audioPlayer == nil {
            try? audioPlayer = AVAudioPlayer(contentsOf: url)
            audioPlayer?.numberOfLoops = numberOfLoops
            audioPlayer?.prepareToPlay()
        }
    }
    
    func play() {
        audioPlayer?.play()
    }
    
    func stop() {
        audioPlayer?.stop()
        audioPlayer = nil
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
